// Copyright (c) [Year] [name of copyright holder]
// [Software Name] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2. 
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2 
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
// See the Mulan PSL v2 for more details.  
// 'use strict';

var vueapp = new Vue({
    data() {
        return {
            key: 1,
            reres: [],
            bg: chrome.extension.getBackgroundPage(),
            curRule: {
                req: '.*test\\.com',
                res: 'http://cssha.com',
                //        type: 'file',
                checked: true
            },
            maps: [],
            editDisplay = 'none',
            editType = '添加',
            inputError = '',
            rules: []
        }
    },
    methods: {
        groupBy(collects, name) {
            let ret = {},
                key;
            collects.forEach(function(elem) {
                let key = elem[name];
                ret[key] = ret[key] || [];
                ret[key].push(elem);
            });
            return ret;
        },
        saveData() {
            this.rules = this.groupBy(this.maps, 'group');
            this.bg.localStorage.ReResMap = JSON.stringify(this.maps);
        },
        virify() {
            if (!this.curRule.req) {
                this.inputError = '正则一栏输入不能为空';
                return false;
            }
            try {
                new RegExp(this.curRule.req);
            } catch (e) {
                this.inputError = 'req正则格式错误';
                return false;
            }
            this.inputError = '';
            return true;
        },
        addRule() {
            if (this.editDisplay === 'none') {
                this.curRule = {
                    req: '.*test\\.com',
                    res: 'http://cssha.com',
                    //                type: 'file',
                    checked: true
                };
                this.editType = '添加';
                this.editDisplay = 'block';
            } else {
                this.editType === '添加' && (this.editDisplay = 'none');
            }
        },
        edit(rule) {
            this.curRule = rule;
            this.editType = '编辑';
            this.editDisplay = 'block';
        },
        copy(rule) {
            this.curRule = JSON.parse(JSON.stringify(rule));
            this.editType = '复制';
            this.editDisplay = 'block';
            //this.maps.push(this.rule);
            // saveData();
        },
        saveRule() {
            if (this.virify()) {
                if (this.editType === '添加') {
                    this.maps.push(this.curRule);
                } else {

                }
                this.saveData();
                this.editDisplay = 'none';
            }
        },
        removeUrl(rule) {
            for (var i = 0, len = this.maps.length; i < len; i++) {
                if (this.maps[i] === rule) {
                    this.maps.splice(i, 1);
                }
            }
            this.saveData();
        },
        export () {
            function saveAs(blob, filename) {
                var type = blob.type;
                var force_saveable_type = 'application/octet-stream';
                if (type && type != force_saveable_type) { // 强制下载，而非在浏览器中打开
                    var slice = blob.slice || blob.webkitSlice;
                    blob = slice.call(blob, 0, blob.size, force_saveable_type);
                }

                var url = URL.createObjectURL(blob);
                var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
                save_link.href = url;
                save_link.download = filename;

                var event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                save_link.dispatchEvent(event);
                URL.revokeObjectURL(url);
            }

            var URL = URL || webkitURL || window;
            var bb = new Blob([JSON.stringify(this.maps, null, '\t')], { type: 'text/json' });
            this.saveAs(bb, 'ReResSetting.json');
        }

    },
    mounted() {
        console.log('reres 初始化');
        this.maps = JSON.parse(this.bg.ReResMap)
        this.rules = this.groupBy(this.bg.ReResMap, 'group');
    },
})
var reres = angular.module('reres', []);


reres.controller('mapListCtrl', function(this) {
    var bg = chrome.extension.getBackgroundPage();

    //保存规则数据到localStorage
    function saveData() {
        this.rules = groupBy(this.maps, 'group');
        bg.localStorage.ReResMap = angular.toJson(this.maps);
    }

    //当前编辑的规则
    this.curRule = {
        req: '.*test\\.com',
        res: 'http://cssha.com',
        //        type: 'file',
        checked: true
    }

    this.maps = bg.ReResMap;
    this.rules = groupBy(bg.ReResMap, 'group');

    //编辑框显示状态
    this.editDisplay = 'none';

    //编辑框保存按钮文本
    this.editType = '添加';

    //输入错误时候的警告
    this.inputError = '';

    //隐藏编辑框
    this.hideEditBox = function() {
        this.editDisplay = 'none';
    }

    //验证输入合法性
    this.virify = function() {
        if (!this.curRule.req) {
            this.inputError = '正则一栏输入不能为空';
            return false;
        }
        try {
            new RegExp(this.curRule.req);
        } catch (e) {
            this.inputError = 'req正则格式错误';
            return false;
        }
        this.inputError = '';
        return true;
    }

    // 点击添加按钮
    this.addRule = function() {
        if (this.editDisplay === 'none') {
            this.curRule = {
                req: '.*test\\.com',
                res: 'http://cssha.com',
                //                type: 'file',
                checked: true
            };
            this.editType = '添加';
            this.editDisplay = 'block';
        } else {
            this.editType === '添加' && (this.editDisplay = 'none');
        }
    };

    //点击编辑按钮
    this.edit = function(rule) {
            this.curRule = rule;
            this.editType = '编辑';
            this.editDisplay = 'block';
        }
        // 复制
    this.copy = function(rule) {
            //this.curRule = rule;
            this.editType = '复制';
            this.editDisplay = 'block';
            //this.maps.push(this.rule);
            // saveData();
        }
        //编辑后保存
    this.saveRule = function() {
        if (this.virify()) {
            if (this.editType === '添加') {
                this.maps.push(this.curRule);
            } else {

            }
            saveData();
            this.editDisplay = 'none';
        }
    };

    //删除规则
    this.removeUrl = function(rule) {
        for (var i = 0, len = this.maps.length; i < len; i++) {
            if (this.maps[i] === rule) {
                this.maps.splice(i, 1);
            }
        }
        saveData();
    }

    //导出
    this.export = function() {
        function saveAs(blob, filename) {
            var type = blob.type;
            var force_saveable_type = 'application/octet-stream';
            if (type && type != force_saveable_type) { // 强制下载，而非在浏览器中打开
                var slice = blob.slice || blob.webkitSlice;
                blob = slice.call(blob, 0, blob.size, force_saveable_type);
            }

            var url = URL.createObjectURL(blob);
            var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
            save_link.href = url;
            save_link.download = filename;

            var event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            save_link.dispatchEvent(event);
            URL.revokeObjectURL(url);
        }

        var URL = URL || webkitURL || window;
        var bb = new Blob([JSON.stringify(this.maps, null, '\t')], { type: 'text/json' });
        saveAs(bb, 'ReResSetting.json');
    }

    //导入
    document.getElementById('jsonFile').onchange = function() {
        var resultFile = this.files[0];
        if (resultFile) {
            var reader = new FileReader();
            reader.readAsText(resultFile);
            reader.onload = function(e) {
                try {
                    var data = JSON.parse(this.result);
                    this.maps.length = 0;
                    for (var i = 0, len = data.length; i < len; i++) {
                        this.maps.push(data[i]);
                    }
                    vueapp.saveData();
                    location.reload();
                } catch (e) {
                    alert("导入失败，请检查文件格式是否正确");
                }
            };
        }
    }
});